// miniprogram/pages/cal_result/cal_result.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    total_amount: 0,
    max_use: 0,
    cb: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let app = getApp();
    let result = this.knapsack_calculate(app.total_amount, app.goods);
    let combine = [];
    for (let k in result.cb){
      combine.push({price: k, num: result.cb[k]})
    }
    this.setData({
      goods: app.goods,
      total_amount: app.total_amount,

      max_use: result.max_use,
      cb: combine
    });
    console.log('this.data', this.data);
  },

  knapsack_calculate: function(amount, goods) {
    let dp = [];
    let combine = [];
    let fee = 0;
    while(fee <= amount){
      if(dp[fee] === undefined){
        dp[fee] = 0;
        combine[fee] = {}
      }
      let good_idx = 0;
      while(good_idx < goods.length){
        let good = goods[good_idx];
        if (fee - good >= 0) {
          if (dp[fee] < dp[fee-good] + good) {
            dp[fee] = dp[fee-good] + good
            combine[fee] = {}
            for (let k in combine[fee-good]){
              combine[fee][k] = combine[fee-good][k];
            }
            combine[fee][good] = (combine[fee][good] || 0) + 1;
          }
        }
        good_idx++;
      }
      fee++;
    }
    return {
      max_use: dp[amount],
      cb: combine[amount],
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})